package com.yyk.yiliao.ui.activity.detail.fragment;


import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.bean.StoreGoodsinfo_Info;
import com.yyk.yiliao.bean.StoreRelationgoods_Info;
import com.yyk.yiliao.ui.home.activity.PharmacyList_Activity;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.util.GlideImageLoader2;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.widget.diver.more.SpacesItemDecoration;
import com.yyk.yiliao.util.ebs.MessageEvent;

import com.yyk.yiliao.util.glide.GlideUtils;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ${zk} on 2018/8/14 0014.
 */

public class Detail_Fragment_One extends BaseFragment {
    public static final String ARGS_PAGE = "Detail_Fragment_One";
    @BindView(R.id.nBanner)
    Banner nBanner;
    @BindView(R.id.nCfysm)
    ImageView nCfysm;
    @BindView(R.id.setting)
    RelativeLayout setting;

    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.bottom_ll)
    LinearLayout bottomLl;
    @BindView(R.id.rv_xgsp)
    RecyclerView rvXgsp;
    @BindView(R.id.nDetailO_enter)
    TextView nDetailOEnter;
    @BindView(R.id.tv_marketvalue)
    TextView tvMarketvalue;
    @BindView(R.id.tv_monthly)
    TextView tvMonthly;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.tv_shopname)
    TextView tvShopname;
    private int id;

    public static Detail_Fragment_One newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        Detail_Fragment_One fragment = new Detail_Fragment_One();
        fragment.setArguments(args);
        return fragment;
    }

    private void initGetIntent() {
        Bundle arguments = getArguments();
        id = arguments.getInt("id");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initGetIntent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //3.取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMoonEvent(MessageEvent messageEvent) {
        id = Integer.parseInt(messageEvent.getMessage());
    }

    /**
     * 相关商品
     *
     * @param map
     */
    private void initShopXiangguan(Map<String, String> map) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postStoreRelationgoods(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<StoreRelationgoods_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(StoreRelationgoods_Info info) {
                        if (info.getCode() == 1) {
                            final List<StoreRelationgoods_Info.DataBean> data = info.getData();
                            Logger.e("相关商品" + info.toString());
                            BaseRecyclerAdapter<StoreRelationgoods_Info.DataBean> adapter = new BaseRecyclerAdapter<StoreRelationgoods_Info.DataBean>(getContext(), data, R.layout.adapter_item_detail_shangpin_xg) {
                                @Override
                                public void convert(BaseRecyclerHolder holder, StoreRelationgoods_Info.DataBean item, int position, boolean isScrolling) {
                                    holder.setText(R.id.tv_marketvalue, "¥ " + item.getMoney());
                                    holder.setText(R.id.tv_name, item.getName());
                                    int recipe = item.getRecipe();
                                    if (recipe == 0) {
                                        holder.getView(R.id.tv_recipe).setVisibility(View.GONE);
                                    } else {
                                        holder.getView(R.id.tv_recipe).setVisibility(View.VISIBLE);
                                    }


                                    GlideUtils.load(getContext(), ApiService.BASE_URL + item.getPic(), (ImageView) holder.getView(R.id.iv_pic));
                                }
                            };
//                            adapter.setLength(3);  这个问题很多
//                            rvXgsp.setLayoutManager(new GridLayoutManager(getActivity(), 3, LinearLayoutManager.VERTICAL, false));
                            rvXgsp.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
                            rvXgsp.addItemDecoration(new SpacesItemDecoration(24, 0, getActivity()));
                            rvXgsp.setAdapter(adapter);
                            adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(RecyclerView parent, View view, int position) {
                                    //商品ID
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("id", data.get(position).getId());
                                    startAct(Detail_Activity.class, bundle);

                                }
                            });
                        }
                    }
                });

    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_detail_one;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        initPost();
    }

    private void initPost() {
        Map<String, String> map = new TreeMap<>();

        map.put("page", 1 + "");
        map.put("id", id + "");
        map.put("sign", Md5Util2.createSign(map));
        initShopOne(map);

        Map<String, String> map2 = new TreeMap<>();

        map2.put("page", 1 + "");
        map2.put("id", id + "");
        map2.put("number", "3");
        map2.put("sign", Md5Util2.createSign(map2));
        initShopXiangguan(map2);


    }

    /**
     * 商品内容
     *
     * @param map
     */
    private void initShopOne(Map<String, String> map) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postStorGoodsinfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<StoreGoodsinfo_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(StoreGoodsinfo_Info info) {
                        Logger.e("商品详情" + info.toString());
                        if (info.getCode() == 1) {
                            //详情
                            StoreGoodsinfo_Info.DataBean data = info.getData();
                            StoreGoodsinfo_Info.DataBean.GoodsinfoBean goodsinfoBean = data.getGoodsinfo().get(0);
                            tvName.setText(goodsinfoBean.getName());
                            tvDescribe.setText(goodsinfoBean.getDescribe());
                            tvShopname.setText(goodsinfoBean.getShopname());
                            tvMonthly.setText("月销" + goodsinfoBean.getMonthly() + "件");
                            tvMarketvalue.setText("¥" + goodsinfoBean.getMarketvalue());
                            int recipe = goodsinfoBean.getRecipe();
                            if (recipe == 0) {
                                nCfysm.setVisibility(View.GONE);
                            } else {
                                nCfysm.setVisibility(View.VISIBLE);
                            }
                            GlideUtils.loadShop(getActivity(), ApiService.BASE_URL + goodsinfoBean.getPic(), ivPic);

                            //设置viewpager
                            List<StoreGoodsinfo_Info.DataBean.GoodsimgsBean> goodsimgs = data.getGoodsimgs();
                            List<String> list = new ArrayList<>();
//                            pic = goodsimgs.get(0).getImg();

                            for (int i = 0; i < goodsimgs.size(); i++) {
                                String img = goodsimgs.get(i).getImg();
                                if (img != null) {
                                    list.add(ApiService.BASE_URL + img);
                                }
                            }
                            if (list.size() > 0) {
                                nBanner.setImages(list);
                                //设置banner样式
                                nBanner.setBannerStyle(BannerConfig.NUM_INDICATOR);//显示数组指示器
                                //设置图片加载器
                                nBanner.setImageLoader(new GlideImageLoader2());
                                nBanner.isAutoPlay(false);
                                //banner设置方法全部调用完毕时最后调用
                                nBanner.start();
                            }
                        }
                    }
                });


    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        nBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        nBanner.stopAutoPlay();
    }


    @OnClick({R.id.nCfysm, R.id.nDetailO_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.nCfysm:
                changeIcon();
                break;
            case R.id.nDetailO_enter:
                Intent intent = new Intent(getContext(), PharmacyList_Activity.class);
                startActivity(intent);
                break;
        }
    }

    // 声明PopupWindow
    private PopupWindow popupWindow;
    // 声明PopupWindow对应的视图
    private View popupView;

    // 声明平移动画
    private TranslateAnimation animation;

    /**
     * 弹出popupWindow处方药说明
     */
    private void changeIcon() {
        if (popupWindow == null) {
            popupView = View.inflate(getActivity(), R.layout.dialog_detail_cfysm, null);
            // 参数2,3：指明popupwindow的宽度和高度
            popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {

                }
            });


            // 设置背景图片， 必须设置，不然动画没作用
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setFocusable(true);

            // 设置点击popupwindow外屏幕其它地方消失
            popupWindow.setOutsideTouchable(true);

            // 平移动画相对于手机屏幕的底部开始，X轴不变，Y轴从1变0
            animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                    Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
            animation.setInterpolator(new AccelerateInterpolator());
            animation.setDuration(500);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow()
                            .getAttributes();
                    lp.alpha = 1.0f;
                    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getActivity().getWindow().setAttributes(lp);
                }
            });
            popupView.findViewById(R.id.queding).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();

                }
            });
        }
        //设置背景透明
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);
        // 在点击之后设置popupwindow的销毁
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }


        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        popupWindow.showAtLocation(getActivity().findViewById(R.id.setting), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupView.startAnimation(animation);
    }
}
